-module(web_sup).
-behaviour(supervisor).

-define(SERVER, ?MODULE).
-export([start_link/0]).
-export([init/1]).


start_link() ->
    supervisor:start_link({local, ?SERVER}, ?MODULE, []).

init([]) ->
    NodeOpts =   cfg:get(ou:get_node_sname(node()), []),
    HOpts =   proplists:get_value(h_opts, NodeOpts, []),
    {ok, RootPath} = file:get_cwd(),
    DocRoot = filename:join([RootPath, "priv", "www"]),
    {ok, _Http}  = mochiweb_http:start_link(make_http_opts(DocRoot, HOpts)),
    {ok, _Https} = mochiweb_http:start_link(make_https_opts(DocRoot, HOpts)),
    {ok, {{one_for_one, 10, 10}, []}}.

make_http_opts(DocRoot, HOpts) ->
    Opts =       proplists:get_value(http_opts, HOpts, [{ip, {0,0,0,0}}, {port, 8442}]),
	ProtoOpts =  make_protocol_opts(HOpts),
    Loop = fun (Req) -> web_loop:loop(Req, DocRoot, ProtoOpts) end,
    [{name, http_loop}, {loop, Loop}|Opts].

make_https_opts(DocRoot, HOpts) ->
    Opts =       proplists:get_value(https_opts, HOpts, [{ip, {0,0,0,0}}, {port, 8443}]),
    ProtoOpts =  make_protocol_opts(HOpts),
    Loop = fun (Req) -> web_loop:loop(Req, DocRoot, ProtoOpts) end,
    {ok, CAPath} = file:get_cwd(),
    [{name, https_loop}, {ssl, true}, {ssl_opts, [{certfile, filename:join([CAPath, "ca", "server_cert.pem"])}, {keyfile, filename:join([CAPath, "ca", "server_key.pem"])}]}, {loop, Loop}|Opts].

make_protocol_opts(HOpts) ->
    case proplists:get_value(proto_opts, HOpts, []) of
        [] -> #{encoder => pb_codec, decoder => pb_codec, handler => msg_handler};
        Opts -> lists:foldl(fun({Key, Values}, Sum) -> maps:put(Key, maps:from_list(Values), Sum) end, #{}, Opts)
    end.